const spdy = require('spdy')
const express = require('express')
const path = require('path')
const fs = require('fs')
const WebSocket = require('ws');
const jsonwebtoken = require('jsonwebtoken')
const secret = "myApp"
const app = express()

app.use('/static', express.static('./static'))

const ico = fs.readFileSync('./static/ohome.ico');

app.use('/',(req,res,next)=>{
    res.push('/favicon.ico', {
        status: 200, // optional
        method: 'GET', // optional
        request: {
            accept: '*/*'
        },
        response: {
            'content-type': 'image/ico'
        }
    }).on('error', function() {}).end(ico);
    next()
})

app.get('/',(req, res)=> {
    const token = jsonwebtoken.sign({name:'liujian'}, secret, { expiresIn:  10 });
    const html = fs.readFileSync('./index.html');
    res.push('/ws', {
        status: 200,
        method: 'GET',
        response: {
            'content-type': 'application/javascript'
        }
    }).on('error', function() {}).end(fs.readFileSync('./static/ws.js').toString());
    res.push('/token',{
        status: 200,
        method: 'GET',
        response: {
            'content-type': 'application/javascript'
        }
    }).end(`var Token = '${token}'`);
    res.send(html.toString());
})


const options = {
    key: fs.readFileSync(__dirname + '/localhost.key'),
    cert:  fs.readFileSync(__dirname + '/localhost.crt'),
}


const server = spdy.createServer(options, app)
const wss = new WebSocket.Server({ server });

wss.on('connection',  (ws)=> {
    ws.on('message', (message)=> {
        message = JSON.parse(message)
        try {
            ws.send(JSON.stringify(jsonwebtoken.verify(message.token, secret)));
        } catch(err) {
            ws.send(JSON.stringify(err));
        }
    });

});
server.listen(3000,()=>{
        console.log(`Server is listening on https://localhost:3000.
    You can open the URL in the browser.`)
    })

